package com.visionet.waveletData.web.web.account;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.visionet.waveletData.web.common.security.password.PwdEncryptor;
import com.visionet.waveletData.web.common.utilities.props.PropsKeys;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;
import com.visionet.waveletData.web.common.utilities.string.StringPool;
import com.visionet.waveletData.web.common.utils.UploadUtil;
import com.visionet.waveletData.web.entity.account.User;
import com.visionet.waveletData.web.service.account.AccountService;
import com.visionet.waveletData.web.service.account.ShiroDbRealm;
import com.visionet.waveletData.web.vo.business.UserInfoVo;
import com.visionet.waveletData.web.web.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springside.modules.mapper.BeanMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/mobile/webUser")
public class UserInfoRestController extends BaseController {
	
	@Autowired
	private AccountService accountService;
	
	// 查询用户列表
	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public ResponseEntity<?> userList(@RequestBody UserInfoVo vo) {
		User user = BeanMapper.map(vo, User.class);

		ShiroDbRealm.ShiroUser suser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if(suser == null){
			throw new RuntimeException("未登录");
		}
		user.setCompany_id(suser.getCompanyId());
		Page<User> page = accountService.findUserInfoByConditionForList(user, vo.getPageInfo());
		List<User> list = page.getContent();
		List<UserInfoVo> volist = new ArrayList<UserInfoVo>();
		UserInfoVo userInfoVo = null;
		if(null != list && list.size()>0){
			for(int i=0;i<list.size();i++){
				User u = list.get(i);
				userInfoVo = new UserInfoVo();
				userInfoVo.setUser_name(u.getUser_name());
				userInfoVo.setUser_type("NORMAL".equals(u.getUser_type())?"普通用户":"管理员");
				userInfoVo.setLast_login_time(u.getLast_login_time());
				userInfoVo.setId(u.getId());
				volist.add(userInfoVo);
			}
		}
		//List<UserInfoVo> volist = BeanMapper.mapList(list, UserInfoVo.class);
		return new ResponseEntity<Page<UserInfoVo>>(GetPageByList(page,volist, UserInfoVo.class),HttpStatus.OK);
	} 
	
	// 查找用户
	@RequestMapping(value = "/getUser/{id}")
	public ResponseEntity<?> getUser(@PathVariable Long id) {
		User user = accountService.findUserInfoByUserId(id);
		Map<String , Object> result = Maps.newHashMap();
		result.put("user", user);
		return new ResponseEntity<Map<String,Object>>(result ,HttpStatus.OK);
	}
	
	// 更新用户
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseEntity<?> updateUserInfo(@RequestBody UserInfoVo vo) throws Exception {
		User po = null;
		if(vo.getId() != null) {
			po = accountService.findUserInfoByUserId(vo.getId());
		} else {
			po = new User();
			User u = accountService.findByLoginName(vo.getUser_name());
			if(u != null) {
				Map<String, Object> result = Maps.newHashMap();
		        result.put("fail", "用户已存在!");
		        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
			}
		}
		
//        SearchFilterUtil.copyBeans(po, BeanConvertMap.map(vo,User.class));
		po.setUser_name(vo.getUser_name());
		String newPassword = new SimpleHash(PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM, //加密算法
											vo.getPass_word(), //密码
											ByteSource.Util.bytes(""), //salt盐
											PwdEncryptor.HASH_INTERATIONS //迭代次数
											).toHex();
		po.setPass_word(newPassword);
		po.setCompany_id(getCurrentUserCompanyId());
        accountService.saveUser(po);
        
        Map<String, Object> result = Maps.newHashMap();
        result.put("success", "保存成功");
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
		//return new ResponseEntity<Map<String, String>>(result,HttpStatus.OK);
	}
	
		
	// 删除用户
	@RequestMapping(value = "/deleteUser/{id}")
	public ResponseEntity<?> deleteUser(@PathVariable Long id) {
		accountService.deleteUserInfo(accountService.findUserInfoByUserId(id));
		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
	}
	

	@RequestMapping("/upload")
	@ResponseBody
	public ResponseEntity<?>upload(HttpServletRequest request) throws Exception{
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<Map<String,Object>> resultList = Lists.newArrayList();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            String fileName = URLDecoder.decode(file.getOriginalFilename(), "UTF-8");
//            String sign = UploadUtil.GetSignByName(fileName);

            Map<String,Object> map = Maps.newHashMap();
            map.put("fileName",fileName);
            String path = PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_ROOT_PATH);
            String[] tempPathArr = UploadUtil.GetPath(fileName, path);
            File file1 = new File(tempPathArr[0]);
            file.transferTo(file1);
            String relativePath=tempPathArr[1];
            System.out.println(PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_DOWNLOAD_PATH)+StringPool.FORWARD_SLASH +relativePath);
            return responseData( PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_DOWNLOAD_PATH)+StringPool.FORWARD_SLASH +relativePath);
        }
        return responseErrorData("未获得数据");

        
	}
	
	@RequestMapping("/download")
	@ResponseBody
	public void downLoad( HttpServletResponse response) throws Exception {
		String filePath = "C:\\mobileAnalytics\\uploadFile\\2017\\01\\13\\a2796f8e-2597-4c83-9de6-f526ad3a8a76-53.java";
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        boolean isOnLine = true;
        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        response.setHeader("fileName", f.getName());
        System.out.println(response.getHeader("fileName"));
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

//	@Autowired
//	private UserInfoService userService;
//	@Autowired
//	private AccountService accountService;
//	@Autowired
//	private ChatConnection chatConnection;
//
//	// 用户列表(手机端缓存,无分页,每次根据最后更新时间来更新用户资料)
//	@RequestMapping(value = "/userContacts", method = RequestMethod.POST)
//	public ResponseEntity<Map<String, Object>> userContacts(@RequestBody Map<String, Object> params) throws Exception {
//		UserInfo userInfo = new UserInfo();
//		String dateStr = (String)params.get("updateDate");
//		userInfo.setUpdateDate(DateUtil.convertFromString(dateStr, DateUtil.YMD_FULL));
////		userInfo.setOrgId(getCurrentOrgId());
//		List<UserInfo> list = userService.findUserInfoByCondition(userInfo, null);
//		Map<String, Object> result = Maps.newHashMap();
//		result.put("userList", BeanMapper.mapList(list, UserInfoVo.class));
//		result.put("lastUpdateDate", DateUtil.convertToString(Calendar.getInstance().getTime()));
//		return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
//	}
//	
//	@RequestMapping(value = "/userList", method = RequestMethod.POST)
//	public ResponseEntity<?> userList(@RequestBody Map<String, Object> params) {
//		UserInfo user = setUser(params);
////		user.setOrgId(getCurrentOrgId());
////		List<UserInfo> list = userService.findUserInfoByConditionForList(user, null).getContent();
//		List<UserInfo> list = new ArrayList<UserInfo>();
//		UserInfo u = new UserInfo();
//		u.setLoginName("AAA");
//		u.setTrueName("张伟俊");
//		u.setTitle("biaoti");
//		u.setPhoneNumber(13812345678l);
//		list.add(u);
//		UserInfo u1 = new UserInfo();
//		u1.setLoginName("AAA");
//		u1.setTrueName("张伟俊");
//		u1.setTitle("biaoti");
//		u1.setPhoneNumber(13812345678l);
//		list.add(u1);
//		UserInfo u2 = new UserInfo();
//		u2.setLoginName("AAA");
//		u2.setTrueName("张伟俊");
//		u2.setTitle("biaoti");
//		u2.setPhoneNumber(13812345678l);
//		list.add(u2);
//		
//		return new ResponseEntity<List<UserInfoVo>>(BeanMapper.mapList(list, UserInfoVo.class), HttpStatus.OK);
//	} 
//	
//	private UserInfo setUser(Map<String, Object> params){
//		UserInfo user = new UserInfo();
//		if(Validator.isNotNull(params.get("userName"))){
//			user.setUserName((String)params.get("userName"));
//			user.setFirstLetter(((String)params.get("userName")).toUpperCase());
//		}
//		return user;
//	}
//	
//	@RequestMapping(value = "/userLists", method = RequestMethod.POST)
//	public ResponseEntity<?> userList(@RequestBody UserInfoVo vo) {
//		UserInfo user = BeanMapper.map(vo, UserInfo.class);
////		user.setOrgId(getCurrentOrgId());
//		Page<UserInfo> page = userService.findUserInfoByConditionForList(user, vo.getPageInfo());
//		List<UserInfo> list = page.getContent();
//		List<UserInfoVo> volist = BeanMapper.mapList(list, UserInfoVo.class);
//		return new ResponseEntity<Page<UserInfoVo>>(GetPageByList(page,volist, UserInfoVo.class),HttpStatus.OK);
//	}
//
//
//    /**
//     * 用户详情
//     */
//	@RequestMapping(value = "/userDetail/{id}", method=RequestMethod.GET)
//	public ResponseEntity<?> userDetailForMobile(@PathVariable Long id){
//		if(Validator.isNull(id)){
//			id = getCurrentUserId();
//		}
//		User user = accountService.getUser(id);
//
////		UserInfoVo vo = BeanMapper.map(user.getUserInfo(), UserInfoVo.class);
////        userService.warpUserDetail(vo);
//		
//		UserInfoVo vo = BeanMapper.map(user, UserInfoVo.class);
//
//		UserVo uvo = BeanMapper.map(user, UserVo.class);
//		uvo.setUserInfo(vo);
//
//        if(id.longValue() == getCurrentUserId().longValue()) {
//            uvo.setDaySign(userService.checkDaySign(id));
//        }
//		return new ResponseEntity<UserVo>(uvo, HttpStatus.OK);
//	}
//
//
////    /**
////     * 获取用户头像
////     * @param id
////     * @return
////     */
////    @RequestMapping(value = "/img/{id}", method=RequestMethod.GET)
////    public ResponseEntity<?> userImage(@PathVariable Long id) {
////        String imgUrl = UserInfoService.getUserImgUrl(id);
////        Map<String, String> map = Maps.newHashMap();
////        map.put("userImgUrl",imgUrl);
////        return new ResponseEntity<Map<String, String>>(map, HttpStatus.OK);
////    }
//
//	
//	// 获取当前月过生日的用户 
//	@RequestMapping(value = "/currMonthBirthUsers", method=RequestMethod.GET)
//	public ResponseEntity<?> currMonthBirthUsers(){
//		return new ResponseEntity<List<UserInfo>>(userService.findCurrMothBirthUser(), HttpStatus.OK);
//	}
//	
//	@RequestMapping(value="/updateUser", method = RequestMethod.POST)
//	public ResponseEntity<?> updateUserForWeb(@RequestBody UserInfoVo vo) throws Exception {
//		updateUser(vo);
//		return new ResponseEntity<Map<String, String>>(GetSuccMap(), HttpStatus.OK);
//	}
//	
//	private void updateUser(UserInfoVo infoVo) throws Exception {
//		if(getCurrentUserId().longValue() != infoVo.getId().longValue()){
//			Map<String,String> messageMap = new HashMap<String,String>();
//			messageMap.put(MobileKey.CODE, BusinessStatus.ACCESSDENIED);
//			messageMap.put(MobileKey.MSG,"Permission error!");
//			throw new RestException(messageMap);
//		}
//
//        infoVo.setUpdateDate(DateUtil.getCurrentDate());
//
//        User po = accountService.getUser(infoVo.getId());
//
////        UserInfo infoPo = po.getUserInfo();
////        SearchFilterUtil.copyBeans(infoPo, BeanConvertMap.map(infoVo,UserInfo.class));
////        if(Validator.isNotNull(infoVo.getUserName())){
////            po.setAliasName(infoVo.getUserName());
////        }
////        po.setUserInfo(infoPo);
//        accountService.saveUser(po);
//	}
//
//	// 更新用户
//	@RequestMapping(value = "/update", method = RequestMethod.POST)
//	public ResponseEntity<?> updateUserInfo(@RequestBody UserInfoVo vo) throws Exception {
//        if(vo.getId()==null){
//            vo.setId(getCurrentUserId());
//        }
//		updateUser(vo);
//		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
//	}
//
//	// 删除用户
//	@RequestMapping(value = "/delUser/{id}")
//	public ResponseEntity<?> delUser(@PathVariable Long id) {
//		userService.deleteUserInfo(userService.findUserInfoByUserId(id));
//		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
//	}
//
//	@RequestMapping(value = "/updateUserImg", method = RequestMethod.POST)
//	public ResponseEntity<?> updateUserImg(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		params.put("isAdmin",BaseController.hasRole(SysConstants.ADMIN) ? "1" : "0");
//		userService.updateUserImg(params, getCurrentUserId());
//		//更新cookie
////		CookieUtil.saveUserInfo(request, response);
//		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
//	}
//	
//
//
//
//	@RequestMapping(value="/setPushSwitch/{status}", method=RequestMethod.GET)
//	public ResponseEntity<?> setPushSwitch(@PathVariable Short status) throws Exception {
//		UserInfo user = userService.findById(getCurrentUserId());
//		if(user.getReceiveMessage() == null || user.getReceiveMessage().shortValue() != status.shortValue()) {
//			user.setReceiveMessage(status);
//			userService.updateUserInfo(user);
//		}
//		return new ResponseEntity<Map<String,String>>(GetSuccMap() ,HttpStatus.OK);
//	}
//	
//	@RequestMapping(value="/validateUserName", method=RequestMethod.POST)
//	public ResponseEntity<?> validateUserName(@RequestBody UserInfo userInfo){
//		Map<String, String> result = Maps.newHashMap();
//		if(Validator.isNull(userInfo.getUserName())){
//			result.put("result", "false");
//		}else if(userInfo.getUserName().equals(getCurrentUserName())){
//			result.put("result", "true");
//			
//		}else{
////			userInfo.setOrgId(getCurrentOrgId());
//			List<UserInfo> list = userService.findUserInfoByCondition(userInfo, null);
//			result.put("result", (list == null || list.size() == 0)?"true":"false");
//		}
//		return new ResponseEntity<Map<String,String>>(result ,HttpStatus.OK);
//	}
//	
//	@RequestMapping(value="/getAttentionList", method=RequestMethod.GET)
//	public ResponseEntity<?> getAttentionList() {
//		List<UserInfo> list = userService.getAttentionList(getCurrentUserId(), null, null).getContent();
//		List<UserInfoVo> volist = BeanMapper.mapList(list, UserInfoVo.class);
//		return new ResponseEntity<List<UserInfoVo>>(volist,HttpStatus.OK);
//	} 
//	
//	@RequestMapping(value="/getAttentionListByPage", method=RequestMethod.POST)
//	public ResponseEntity<?> getAttentionListByPage(@RequestBody UserInfoVo vo) {
//        if(vo.getId()==null){
//            vo.setId(getCurrentUserId());
//        }
//		Page<UserInfo> page = userService.getAttentionList(vo.getId(), vo.getUserName(), vo.getPageInfo());
//		List<UserInfo> list = page.getContent();
//		List<UserInfoVo> volist = BeanMapper.mapList(list, UserInfoVo.class);
//		return new ResponseEntity<Page<UserInfoVo>>(GetPageByList(page, volist, UserInfoVo.class),HttpStatus.OK);
//	} 
//	
//	@RequestMapping(value="/findUsersByIntegral", method=RequestMethod.GET)
//	public ResponseEntity<?> findUsersByIntegral() {
////		List<UserInfoVo> list = userService.findUsersByIntegral(getCurrentOrgId());
////		return new ResponseEntity<List<UserInfoVo>>(list,HttpStatus.OK);
//		return null;
//	} 
//	
//
//
//
//
//
//
}
